﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace EVTEST
{
    public struct EvDataModel
    {
        public bool isnumber;
        public string datastr;
        public double datavalue;
        public int digits;
        public string unit;
        public string title;
    }
    public struct Data_chargeResult
    {
        public List<double> BatteryMaxTemp;
        public List<double> BatteryCellMaxVolt;
        public List<double> BatteryCellMinVolt;
        public List<double> BatteryCellDivVolt;
        public double Process_BatteryMaxTemp;
        public double Process_BatteryCellMaxVolt;
        public double Process_BatteryDivVolt;
    }
    public struct Data_dynaResult
    {
        public List<double> BatteryMaxTemp;
        public List<double> BatteryCellMinVolt;
        public List<double> MotorTemp;
        public List<double> MCSTemp;
        public List<double> DCDCTemp;
        public List<double> Speed;
        public List<double> Force;
        public double Process_BatteryMaxTemp;
        public double Process_BatteryCellMinVolt;
        public double Process_MotorTemp;
        public double Process_MCSTemp;
        public double Process_DCDCTemp;
    }
    public struct Data_charge
    {
        public string BatteryMaxTemp;// 动力蓄电池最高温度 字符串 否 ℃
        public string BatteryCellMaxVolt;// 单体电池最高电压 字符串 否 V
        public string BatteryCellVoltRange;// 单体蓄电池电压极差 字符串 否 V
        public string BatteryMaxTempNum;// 单体蓄电池最高温度所在编号 字符串 否
        public string BatteryCellMaxVoltNum;// 单体蓄电池最高电压所在编号 字符串 否
        public string BatteryMinTemp;// 单体蓄电池最低温度 字符串 否 ℃
        public string BatteryMinTempNum;// 单体蓄电池最低温度所在编号 字符串 否 ℃
        public string ChargingVoltageMeter;// 充电电压测量值 字符串 否 V
        public string ChargingCurrentMeter;// 充电电流测量值 字符串 否 A
        public string SOC;//当前荷点状态 SOC 字符串 否 %
        public string OutputVoltage;// 电压输出值 字符串 否 V
        public string OutputCurrent;//电流输出值 字符串 否 A
        public string DemandVoltage;// 电压需求 字符串 否 V
        public string DemandCurrent;//电流需求 字符串 否 A
        public string ChargingMode;//充电模式(1:恒压；2：恒流) 字符串 否
        public string MaxAllowChargingVoltage;// 单体动力电池最高允许充电电压 字符串 否 V
        public string MaxAllowChargingCurrent;// 最高允许充电电流 字符串 否 A
        public string TotalEnergy;// 动力电池标称总能量 字符串 否 Kw·h
        public string MaxAllowTotalVoltage;// 最高允许充电总电压 字符串 否 V
        public string MaxAllowChargingTemp;// 最高允许充电温度 字符串 否 ℃
        public string VehicleSOC;// 整车动力蓄电池荷点状态 字符串 否 %
        public string BatteryVoltage;//整车动力蓄电池当前电池电压 字符串 否 V
        public string BatteryType;// 电池类型 字符串 否
        public string BatteryPackNum;// BMS 电池组序号 字符串 否
        public string BatteryCellMinVolt;// 单体电池最低电压 字符串 是
    }

    public struct Data_DWDS_DCPEAndACPE
    {
        public string value;// 可导电外壳与可导电外壳间电位均衡
    }
    public struct Data_DWDS_PEAndShellPE
    {
        public string value;// 外壳与电平台间电位均衡
    }
    public struct Data_JYDZ_DC
    {
        public string IRDCChargeSocket;// 直流充电插座绝缘电阻
        public string IRDCPositiveAndPE;//DC+和 PE 绝缘电阻字符串 否 MΩ
        public string IRDCNegativeAndPE;//DC-和 PE 绝缘电阻字符串 否 MΩ
    }
    public struct Data_JYDZ_AC
    {
        public string IRACChargeSocket;// 交流充电插座绝缘电阻
        public string IRL1;// L1 与 PE 字符串 否 MΩ
        public string IRL2;// L2 与 PE 字符串 否 MΩ
        public string IRL3;// L3 与 PE 字符串 否 MΩ
    }
    public abstract class EVChargeParent
    {
        public controller.myLED myLED_OBD_connected = null, myLED_OBD_data = null;
        public double GetDouble(string str, double nullvalue = -99)
        {
            if (!String.IsNullOrEmpty(str))
            {
                double temp = 0;
                if (double.TryParse(str, out temp))
                {
                    return temp;
                }
                else
                    return nullvalue;
            }
            else
            {
                return nullvalue;
            }
        }
        public int GetInt(string str, int nullvalue = -99)
        {
            if (!String.IsNullOrEmpty(str))
            {
                int temp = 0;
                if (int.TryParse(str, out temp))
                {
                    return temp;
                }
                else
                    return nullvalue;
            }
            else
            {
                return nullvalue;
            }
        }
        /// <summary>
        /// 开始OBD服务，初始化OBD实例后调用
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public abstract bool startService(out string msg);
        /// <summary>
        /// 停止OBD服务，无需调用
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public abstract bool stopService(out string msg);
        public abstract bool startChargeTest(out string code,out string msg);
        public abstract bool getChargeTestData(out Data_charge data, out bool isStartCharge, out string code, out string msg);
        public abstract bool testDWDS_DCPEAndACPE(out string code, out string msg);
        public abstract bool getDWDS_DCPEAndACPEData(out Data_DWDS_DCPEAndACPE data, out string code, out string msg);
        public abstract bool testDWDS_PEAndShellPE(out string code, out string msg);
        public abstract bool getDWDS_PEAndShellPEData(out Data_DWDS_PEAndShellPE data, out string code, out string msg);
        public abstract bool testJYDZ_DC(out string code, out string msg);
        public abstract bool getJYDZ_DCData(out Data_JYDZ_DC data, out string code, out string msg);
        public abstract bool testJYDZ_AC(out string code, out string msg);
        public abstract bool getJYDZ_ACData(out Data_JYDZ_AC data, out string code, out string msg);
        public abstract bool abortTest(out string code, out string msg);
        public abstract bool getChargeResultData(out Data_charge data, out string code, out string msg);
    }

    /// <summary>
    /// 配合安装程序接收安装配置信息和获取配置信息
    /// </summary>
    public class JbtXmlHandler
    {
        /// <summary>
        /// 保存安装时的配置信息
        /// </summary>
        /// <param name="path">安装目录</param>
        /// <param name="folder">配置的文件保存目录</param>
        public static void UpdateSaveFolder(string path, string folder)
        {
            try
            {
                XmlTextWriter xmlWriter = new XmlTextWriter(path + "\\Default.config", Encoding.UTF8);
                xmlWriter.WriteStartDocument();
                xmlWriter.WriteStartElement("Default");
                xmlWriter.WriteStartElement("SaveFoler", "");
                xmlWriter.WriteString(folder);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("WorkFoler", "");
                xmlWriter.WriteString(path);
                xmlWriter.WriteEndElement();

                xmlWriter.WriteEndDocument();
                xmlWriter.Close();
            }
            catch (Exception ex)
            {

            }
        }
        /// <summary>
        /// 获取保存目录（工作目录）
        /// </summary>
        /// <returns>工作目录</returns>
        public static string GetSaveFolder()
        {
            string strSaveFolder = AppDomain.CurrentDomain.BaseDirectory;// Environment.CurrentDirectory;// @"D:\SaveFolder";
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(AppDomain.CurrentDomain.BaseDirectory + "\\Default.config");

                XmlNode xnRoot = doc.SelectSingleNode("Default");
                XmlNodeList xnl = xnRoot.ChildNodes;
                foreach (XmlNode xn in xnl)
                {
                    XmlElement xe = (XmlElement)xn;
                    byte[] bts = Encoding.UTF8.GetBytes(xe.Name);
                    if (xe.Name == "SaveFoler")
                    {
                        strSaveFolder = xe.InnerText;
                        byte[] bt = Encoding.UTF8.GetBytes(strSaveFolder);
                        break;
                    }
                }

            }
            catch (Exception ex)
            {

            }
            return strSaveFolder;
        }
        /// <summary>
        /// 获取应用程序安装（运行）目录
        /// </summary>
        /// <returns>应用程序安装（运行）目录</returns>
        public static string GetAppFolder()
        {
            string strSaveFolder = AppDomain.CurrentDomain.BaseDirectory;//Environment.CurrentDirectory;// @"D:\SaveFolder";
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(AppDomain.CurrentDomain.BaseDirectory + "\\Default.config");

                XmlNode xnRoot = doc.SelectSingleNode("Default");
                XmlNodeList xnl = xnRoot.ChildNodes;
                foreach (XmlNode xn in xnl)
                {
                    XmlElement xe = (XmlElement)xn;
                    byte[] bts = Encoding.UTF8.GetBytes(xe.Name);
                    if (xe.Name == "WorkFoler")
                    {
                        strSaveFolder = xe.InnerText;
                        byte[] bt = Encoding.UTF8.GetBytes(strSaveFolder);
                        break;
                    }
                }

            }
            catch (Exception ex)
            {

            }
            return strSaveFolder;
        }

    }
    /// <summary>
    /// 日志记录类
    /// </summary>
    public class LogWrite
    {
        static string s_strWorkFolder = null;
        /// <summary>
        /// 互斥对象，防止多线程读写冲突
        /// </summary>
        static object mutex = new object();
        /// <summary>
        /// 输出提示信息
        /// </summary>
        /// <param name="msg">提示信息</param>
        static public void WriteInfo(string msg)
        {
            // 获取工作目录
            if (string.IsNullOrEmpty(s_strWorkFolder))
            {
                s_strWorkFolder = JbtXmlHandler.GetSaveFolder();
                if (!Directory.Exists(s_strWorkFolder))
                {
                    Directory.CreateDirectory(s_strWorkFolder);
                }
                s_strWorkFolder += "\\OBD_Log";
                if (!Directory.Exists(s_strWorkFolder))
                {
                    Directory.CreateDirectory(s_strWorkFolder);
                }
            }
            // 保存目录
            string strFolder = string.Format("{0}\\{1}", s_strWorkFolder, DateTime.Now.ToString("yyyyMMdd"));
            // 保存位置
            string strFileName = string.Format("{0}\\{1}_Info.txt", strFolder, DateTime.Now.ToString("yyyyMMdd_HH"));
            #region 生成目录
            if (!Directory.Exists(strFolder))
            {
                Directory.CreateDirectory(strFolder);
            }
            #endregion
            #region 写入文件内容
            lock (mutex)
            {
                FileMode fm = FileMode.OpenOrCreate;
                if (File.Exists(strFileName))
                {
                    fm = FileMode.Append;
                }
                using (FileStream fs = new FileStream(strFileName, fm))
                {
                    using (BufferedStream bs = new BufferedStream(fs))
                    {
                        using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
                        {
                            //sw.WriteLine(string.Format("{0} Info:{1}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss:fff"), SimpleCrypto1.EncryptText(msg,"0123456789012345")));
                            sw.WriteLine(string.Format("{0} Info:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"), msg));
                        }
                    }
                }
            }
            #endregion
        }

        /// <summary>
        /// 输出错误信息
        /// </summary>
        /// <param name="msg"></param>
        static public void WriteError(string msg)
        {
            // 获取工作目录
            if (string.IsNullOrEmpty(s_strWorkFolder))
            {
                s_strWorkFolder = JbtXmlHandler.GetSaveFolder();
                if (!Directory.Exists(s_strWorkFolder))
                {
                    Directory.CreateDirectory(s_strWorkFolder);
                }
                s_strWorkFolder += "\\OBD_Log";
                if (!Directory.Exists(s_strWorkFolder))
                {
                    Directory.CreateDirectory(s_strWorkFolder);
                }
            }
            // 保存目录
            string strFolder = string.Format("{0}\\{1}", s_strWorkFolder, DateTime.Now.ToString("yyyyMMdd"));
            // 保存位置
            string strFileName = string.Format("{0}\\{1}_Info.txt", strFolder, DateTime.Now.ToString("yyyyMMdd_HH"));
            #region 生成目录
            if (!Directory.Exists(strFolder))
            {
                Directory.CreateDirectory(strFolder);
            }
            #endregion
            lock (mutex)
            {
                #region 写入文件内容
                FileMode fm = FileMode.OpenOrCreate;
                if (File.Exists(strFileName))
                {
                    fm = FileMode.Append;
                }
                using (FileStream fs = new FileStream(strFileName, fm))
                {
                    using (BufferedStream bs = new BufferedStream(fs))
                    {
                        using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
                        {
                            sw.WriteLine(string.Format("{0} Error:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"), msg)); ;
                        }
                    }
                }
                #endregion
            }
        }
    }
}
